﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Interop;

namespace WpfImageDuplicates
{
    public enum UpdateAction
    {
        None = 0,
        Load = 1,
        Unload = 2,
    }
    /// <summary>
    /// Interaction logic for FullImageView.xaml
    /// </summary>
    public partial class ThumbnailView : UserControl
    {
        private bool _dirty;

        public event EventHandler<ObjectEventArgs<FileImageViewModel>> WantView;

        public static readonly DependencyProperty FileImageViewModelProperty =
            DependencyProperty.Register("FileImageViewModel", typeof(FileImageViewModel), typeof(ThumbnailView), new PropertyMetadata(null, OnFileImageViewModelPropertyChanged));

        public FileImageViewModel FileImageViewModel
        {
            get { return (FileImageViewModel)GetValue(FileImageViewModelProperty); }
            set { SetValue(FileImageViewModelProperty, value); }
        }

        public bool Dirty
        {
            set { _dirty = value; }
        }

        private static void OnFileImageViewModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ThumbnailView source = d as ThumbnailView;

            FileImageViewModel vOld = e.OldValue as FileImageViewModel;
            FileImageViewModel vNew = e.NewValue as FileImageViewModel;

            source.UpdateFileImageViewModel(vOld, vNew);
        }

        private void UpdateFileImageViewModel(FileImageViewModel viewModelOld, FileImageViewModel viewModelNew)
        {
            FileImageViewModel = viewModelNew;

            if (viewModelOld != null)
            {
                viewModelOld.DataLoaded -= _viewModel_DataLoaded;
            }

            // Let the UI bind to the view-model.
            this.DataContext = FileImageViewModel;

            this.txtFileName.Text = FileImageViewModel.FileNameOnly;
            FileImageViewModel.DataLoaded += new EventHandler<ObjectEventArgs<string>>(_viewModel_DataLoaded);

            _dirty = true;
        }

        void _viewModel_DataLoaded(object sender, ObjectEventArgs<string> e)
        {
            bool? visible = this.GetIsVisibleInScroller(null);

            if (visible == null)
            {
                return;
            }

            bool vis = visible == true ? true : false;

            if (vis)
            {
                if (this.FileImageViewModel.Thumbnail != null)
                {
                    SetImageToThumbnail();
                    imgMain.InvalidateVisual();
                }
            }
            else
            {
                _dirty = true;
            }
        }

        public ThumbnailView()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(ThumbnailView_Loaded);
        }

        void ThumbnailView_Loaded(object sender, RoutedEventArgs e)
        {
            btnImage.Width = Settings.Values.ThumbWidth;
            btnImage.Height = Settings.Values.ThumbHeight;
                
            bool? visible = this.GetIsVisibleInScroller(null);

            if (visible == null)
                return;

            UpdateIfDirty(visible == true, false);
        }


        public UpdateAction UpdateIfDirty(bool vis, bool skip)
        {
            if (!skip && !vis && !FileImageViewModel.SuspendUnload)
            {
                imgMain.Source = null;

                // outside visual viewing area
                if (FileImageViewModel.BitmapImageLoaded)
                {
                    FileImageViewModel.FreeBitmapImage(true);
                    _dirty = true;
                    return UpdateAction.Unload;
                }
            }
            else
            {
                if (_dirty && !FileImageViewModel.SuspendUnload)
                {
                    _dirty = false;
                    SetImageToThumbnail();
                    return UpdateAction.Load;
                }
            }
            return UpdateAction.None;
        }

        public void SetImageToThumbnail()
        {
            var thumb = FileImageViewModel.Thumbnail;

            if (thumb != null)
            {
                BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromWidthAndHeight(thumb.Width, thumb.Height);
                var src = thumb.CreateImageSourceFromBitmap(sizeOptions);

                imgMain.Width = Settings.Values.ThumbWidth;
                imgMain.Height = Settings.Values.ThumbHeight;
                btnImage.Width = Settings.Values.ThumbWidth;
                btnImage.Height = Settings.Values.ThumbHeight;
                gridMain.Width = Settings.Values.ThumbWidth;
                gridMain.Height = Settings.Values.ThumbHeight + 14;

                if (imgMain.Source == null)
                {
                    imgMain.Source = src;
                }
            }
        }

        private void btnImage_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (WantView != null)
                WantView(this, new ObjectEventArgs<FileImageViewModel>(FileImageViewModel));

            e.Handled = true;
        }
    }
}
